var jsMods = ['vue'];
var stampMainVm;
CafeJS.models(jsMods, function(Vue) {
    stampMainVm = new Vue({
        el: '#stampMain',
        data: {
            isShow: true,
            bigStampMapPopUp: null,
            bigMapResult: null,
            bigstampRoute: "business/template/bigstamp-pop.html",
            queryDataClickCount: 0,
            selectedTime: {
                getDataUrl: "/drawmake/makedraw/getThumbImg",
            },
            //区域选择
            selectArea: 2,
            areas: [{
                key: '0',
                name: '天津'
            }, {
                key: '2',
                name: '海河'
            }],
            // 模式选择
            selectedModel: 'EC',
            //区域选择是否禁用
            isDisable: true,
            models: [{
                    key: 'EC',
                    name: 'EC',
                    chinese: 'EC模式',
                },
                {
                    key: 'NWGD',
                    chinese: 'NWGD',
                    name: 'NWGD'
                },
                {
                    key: 'TJWRF',
                    chinese: 'TJWRF',
                    name: 'TJWRF'
                },
                {
                    key: 'GFS',
                    chinese: 'GFS',
                    name: 'GFS'
                },
                // {
                //     key: 'FUSH',
                //     chinese: 'FUSH',
                //     name: 'FUSH'
                // }
            ],
            // 要素
            selectedEle: 'TP12H',
            eles: [{
                    key: 'TP1H',
                    name: '1h降水',
                    unit: 'mm',
                    aging: 1
                },
                {
                    key: 'TP3H',
                    name: '3h降水',
                    unit: 'mm',
                    aging: 3
                }, {
                    key: 'TP6H',
                    name: '6h降水',
                    unit: 'mm',
                    aging: 6
                },
                {
                    key: 'TP12H',
                    name: '12h降水',
                    unit: 'mm',
                    aging: 12
                },
                {
                    key: 'TP24H',
                    name: '24h降水',
                    unit: 'mm',
                    aging: 24
                }
            ],
            eleSx: {
                'EC': { 'startSx': '000', 'endSx': '240' },
                'NWGD': { 'startSx': '000', 'endSx': '240' },
                'TJWRF': { 'startSx': '000', 'endSx': '096' },
                'GFS': { 'startSx': '000', 'endSx': '240' },
                'FUSH': { 'startSx': '000', 'endSx': '240' }
            },
            agings: {
                start: '0',
                end: '240',
                interval: {
                    'TP1H': 1,
                    'TP3H': 3,
                    'TP6H': 6,
                    'TP12H': 12,
                    'TP24H': 24,
                },
                colorLegend: {
                    'TP1H': '/business/szyb/css/images/legend/color_tp1h_000.png',
                    'TP3H': '/business/szyb/css/images/legend/color_tp3h_000.png',
                    'TP6H': '/business/szyb/css/images/legend/color_tp6h_000.png',
                    'TP12H': '/business/szyb/css/images/legend/color_tp12h_000.png',
                    'TP24H': '/business/szyb/css/images/legend/color_tp24h_000.png',
                },
            },
            stampMapResults: [],
            stampMapLegend: '',
            datepicker: null,
            title: 'EC模式12小时降水（mm）多时效对比邮票图（时效：0-60）',
            startTimeList: [],
            endTimeList: [],
        },
        mounted: function() {
            this.init();
        },
        methods: {
            init: function() {
                $('.stampContentWrap').height($("#modal_stamp").height() - 120);
                $('.stampContentWrap').width($("#modal_stamp").width() - 45);

                this.refreshTime();
                this.refreshTimeList();
                this.queryData();
            },

            refreshTime: function() {
                var _this = this;
                _this.selectedTime.latesttime = $("#date").IDatePicker().getVal() + ":00";
                $("#stamp-datePicker").val(_this.selectedTime.latesttime);
                $.IDate(".stamp-datePanel", {
                    query: function query() {
                        stampMainVm.queryData();
                    }
                });
                this.datepicker = $("#stamp-datePicker").IDatePicker()
            },

            refreshTimeList: function() {
                var _this = this;
                _this.startTimeList.splice(0);
                _this.endTimeList.splice(0);
                _this.startTimeList.push('000');
                var interval = _this.agings.interval[_this.selectedEle];
                var aging = Number(interval);
                var start = Number(_this.eleSx[_this.selectedModel]["startSx"]);
                var end = Number(_this.eleSx[_this.selectedModel]["endSx"]);
                while (aging <= end) {
                    if (aging >= start) {
                        _this.startTimeList.push((Array(3).join('0') + aging).slice(-3));
                        _this.endTimeList.unshift((Array(3).join('0') + aging).slice(-3));
                    }
                    aging += interval;
                }
                this.agings.start = _this.startTimeList[0];
                this.agings.end = _this.endTimeList[0];
            },

            getTitle: function() {
                var _this = this;
                var ele, mm, chinese = "";
                _this.eles.forEach(function(e) {
                    if (e.key == _this.selectedEle) {
                        ele = e.name;
                        mm = e.unit;
                        return false;
                    }
                })
                _this.models.forEach(function(m) {
                    if (m.key == _this.selectedModel) {
                        chinese = m.chinese;
                        return false;
                    }
                })
                var time = dateUtil.convertStringToDate8(_this.getStartTime());
                this.title = chinese + '细网格' + ele + '( ' + mm + ' )邮票图（起报时间：' + time + '时   时效：' + Number(_this.agings.start) + '-' + Number(_this.agings.end) + '）';
            },
            getStartTime: function() {
                var startTimeDate = new Date(this.datepicker.getVal() + ":00:00").format("yyyyMMddhhmmss");
                return startTimeDate;
            },
            //选择的要素
            getSelectedKeys: function(agingList) {
                var _this = this;
                var agingAttr = [];
                var startTime = this.getStartTime();

                var interval = this.agings.interval[this.selectedEle];

                var aging = Number(interval);
                var start = Number(this.agings.start) || 0;
                var end = Number(this.agings.end) || 0;
                while (aging <= end) {
                    if (aging >= start) {
                        agingAttr.push((Array(3).join('0') + aging).slice(-3));
                    }
                    aging += interval;
                }

                var orginAgings = agingAttr.join(',');
                agingAttr = agingList || agingAttr;

                var agings = agingAttr.join(',');

                return {
                    agingAttr: agingAttr,
                    startTime: startTime,
                    interval: interval,
                };
            },

            //分批查询 
            queryData: function() {
                var _this = this;
                if (Number(_this.agings.interval.start) > Number(_this.agings.interval.end)) {
                    alert("预报时效开始时间不能大于结束时间");
                    return;
                }
                this.queryDataClickCount++;
                var clickCount = this.queryDataClickCount;
                var selectedKeys = _this.getSelectedKeys();
                var agingList = selectedKeys.agingAttr; //时效数组
                var n = 1;
                var agingList2d = [];
                if (agingList.length > n) {
                    var nIndex = -1; //二维数组第一层下标
                    var mIndex = 0; //二维数组第二层下标
                    agingList.forEach(function(ag, i) {
                        if (i % n == 0) {
                            nIndex++;
                            mIndex = 0;
                        }
                        agingList2d[nIndex] = agingList2d[nIndex] || [];
                        agingList2d[nIndex][mIndex] = ag;
                        mIndex++;
                    });
                } else {
                    agingList2d[0] = agingList;
                }

                _this.getTitle();
                _this.stampMapLegend = this.agings.colorLegend[this.selectedEle];

                _this.stampMapResults.splice(0);
                agingList2d.forEach(function(a) {
                    _this.stampMapResults.push({});
                })
                agingList2d.forEach(function(ags, j) {
                    _this.queryDataExe(ags, clickCount, j);
                });
            },
            /**
             * 查询方法
             * @param agingList 时效数组
             * @param last 是否是最后一次
             * @param clickCount 查询按钮点击次数
             */
            queryDataExe: function(agingList, clickCount, agingList2dIndex) {
                var _this = this;

                var selectedKeys = _this.getSelectedKeys(agingList);
                var url = _this.selectedTime.getDataUrl;

                $.get(url, {
                        fcstTime: selectedKeys.startTime,
                        element: "TP1H",
                        mode: _this.selectedModel,
                        startP: (Number(selectedKeys.agingAttr[0]) - selectedKeys.interval > 9 ? "0" : "00") + Number(selectedKeys.agingAttr[0]) - selectedKeys.interval,
                        endP: Number(selectedKeys.agingAttr[0]),
                        range: _this.selectArea
                    },
                    function(result) {

                        if (clickCount < _this.queryDataClickCount) {
                            return;
                        }

                        var data = "";
                        if (result) {
                            data = result;
                        }
                        selectedKeys.agingAttr.forEach(function(a, index) {
                            var agingSort = Number(a);
                            var interval = selectedKeys.interval;

                            var key = _this.selectedModel + '_' + selectedKeys.startTime + '_' + a;

                            var titleStartTime = dateUtil.convertStringToDate8(selectedKeys.startTime);
                            titleStartTime.setHours(titleStartTime.getHours() + (agingSort - interval));

                            var titleEndTime = dateUtil.convertStringToDate8(selectedKeys.startTime);
                            titleEndTime.setHours(titleEndTime.getHours() + agingSort);
                            _this.stampMapResults.splice(agingList2dIndex, 1, {
                                title: _this.selectedEle.indexOf("TP") != -1 ? (dateUtil.convertDateToString(titleStartTime, "ddhh") +
                                    '-' + dateUtil.convertDateToString(titleEndTime, "ddhh")) : (dateUtil.convertDateToString(titleEndTime, "ddhh")),
                                url: data ? ("data:img/png;base64," + data) : '',
                                time: selectedKeys.startTime,
                                mode: _this.selectedModel,
                                startP: (Number(selectedKeys.agingAttr[0]) - selectedKeys.interval > 9 ? "0" : "00") + Number(selectedKeys.agingAttr[0]) - selectedKeys.interval,
                                endP: Number(selectedKeys.agingAttr[0]),
                                range: _this.selectArea,
                                element: "TP1H",
                            });

                        });

                        setTimeout(function() {
                            var height = !($(".stampMapBoxImg").height()) ? 256.94 : $(".stampMapBoxImg").height();
                            $(".stampMapBox").css({
                                "height": height,
                            });
                        }, 100)
                    }, "text");

            },
            getStampMapBox: function(url) {
                if (!url) {
                    return 'stampMapBox  bgNothing';
                } else {
                    return 'stampMapBox';
                }
            },
            /**
             * 打开大图
             */
            opengBigImg: function(stampMapResult) {
                if (!stampMapResult.url) {
                    alert("无产品");
                    return;
                }
                var width = $("#modal_stamp").width();
                var height = $("#modal_stamp").height();
                this.bigStampMapPopUp = CafeJS.ModalBox({
                    id: "bigStampMapPopUp",
                    container: 'cafe-busis-container',
                    title: '',
                    url: this.bigstampRoute,
                    width: width,
                    height: height,
                    m_left: $("#modal_stamp").css("left"),
                    m_top: $("#modal_stamp").css("top"),
                    hide: true,
                    closed: function() {
                        CafeJS.ModalBoxClose("bigStampMapPopUp");
                    }
                });
                this.bigMapResult = stampMapResult;
            },

            insertArray: function(arr, item, index) {
                var a = arr.slice(0);
                a.splice(index, 0, item);
                return a;
            },
            changeStartTime: function(model) {
                this.agings.start = model.target.value;
                this.queryData();
            },
            changeEndTime: function(model) {
                this.agings.end = model.target.value;
                this.queryData();
            },
            changeEle: function() {
                this.refreshTimeList();
                this.queryData();
            },
            forward: function() {
                $("#stamp-datePicker").IDatePicker().toForward();
                this.queryData();
            },
            backward: function() {
                $("#stamp-datePicker").IDatePicker().toBackward();
                this.queryData();
            },
            newest: function() {
                $("#stamp-datePicker").IDatePicker().toNewest();
                this.queryData();
            },
            changeArea: function() {
                this.queryData();
            },
            changeMode: function() {
                this.refreshTimeList();
                this.queryData();
            }
        }
    });
});